<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { toNumber } from 'lodash-es'
import type { FormType } from './index'
import { GetDataDetail, PostCreateData, PutModifyData } from '@/api/modules/screen'
import { GetOptionData } from '@/api/modules/clientAccount'
import { GetOptionData as GetIdOptionData } from '@/api/modules/drawact'
import { GetOptionData as GetStoreOption } from '@/api/modules/store'
import detailStore from '@/store/modules/cacheData'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const imgDomain = 'https://img1.eprhan.cc'

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormType>({
  name: '',
  machineCode: '',
  vid: 0,
  drawId: 0,
  storeId: 0,
  bannerJson: [],
  qvQrCodePic: '',
})

const OptionObj = reactive({
  clientAccountOption: [],
  drawactOption: [],
  stoerOption: [],
})
const id = route.query.id as string

function handleUploadSuccess(urls: string) {
  ruleForm.value.qvQrCodePic = urls
}

// 提交
async function SubmitData() {
  const params = ruleForm.value
  // params.bannerJson = (ruleForm.value.bannerJson as string[]).join(',')
  params.bannerJson = (params.bannerJson as string[]).map((item: string) => imgDomain + item)
  params.bannerJson = JSON.stringify(params.bannerJson)
  if (id) {
    // 编辑
    ruleForm.value.id = toNumber(id)
    PutModifyData(ruleForm.value).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('编辑成功')
        router.push({ name: 'screenIndex' })
      }
      else {
        if (typeof res.errors === 'string') {
          ElMessage.error(`编辑失败。${res.errors}`)
        }
        else {
          let errorStr = ''
          for (const key in res.errors) {
            errorStr += `${key}：${res.errors[key]}；`
          }
          ElMessage.error(`编辑失败。${errorStr}`)
        }
      }
    })
  }
  else {
    // 添加
    PostCreateData(ruleForm.value).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('添加成功')
        detailData.EmptyScreen()
        router.push({ name: 'screenIndex' })
      }
      else {
        if (typeof res.errors === 'string') {
          ElMessage.error(`添加失败。${res.errors}`)
        }
        else {
          let errorStr = ''
          for (const key in res.errors) {
            errorStr += `${key}：${res.errors[key]}；`
          }
          ElMessage.error(`添加失败。${errorStr}`)
        }
      }
    })
  }
}

function ClearBlank() {
  ruleForm.value.machineCode = ruleForm.value.machineCode.replace(/\s/g, '')
}

watch(ruleForm, (newValue) => {
  if (!id) {
    detailData.RememberScreen(newValue)
  }
}, { deep: true })

onMounted(async () => {
  if (id) {
    await GetDataDetail(id).then(async (res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
        ruleForm.value.bannerJson = (ruleForm.value.bannerJson as string).replace(/[[\]"]/g, '')
        ruleForm.value.bannerJson = ruleForm.value.bannerJson.split(',')
        ruleForm.value.bannerJson = (ruleForm.value.bannerJson as string[]).map((item: string) => item.slice(22))
      }
    })
  }
  else {
    ruleForm.value = detailData.GetScreenData()
  }
  const data = await GetOptionData()
  OptionObj.clientAccountOption = data.data
  const data1 = await GetIdOptionData()
  OptionObj.drawactOption = data1.data
  const data2 = await GetStoreOption()
  OptionObj.stoerOption = data2.data
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="大屏名称">
              <el-input v-model="ruleForm.name" style="width: 300px;" placeholder="请输入大屏名称" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="机器码">
              <el-input v-model="ruleForm.machineCode" style="width: 300px;" placeholder="请输入机器码" @blur="ClearBlank" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="企微用户">
              <!-- <el-input v-model="ruleForm.vid" type="number" style="width: 300px;" placeholder="请输入企微用户ID" /> -->
              <el-select v-model="ruleForm.vid" placeholder="请选择企微用户" style="width: 300px;">
                <el-option
                  v-for="items in (OptionObj.clientAccountOption as any)" :key="items.id" :label="items.realname" :value="items.vid"
                />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="抽奖活动ID">
              <el-select v-model="ruleForm.drawId" placeholder="请选择抽奖活动" style="width: 300px;">
                <el-option
                  v-for="items in (OptionObj.drawactOption as any)" :key="items.drawId" :label="items.drawId" :value="items.drawId"
                />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="门店">
              <el-select v-model="ruleForm.storeId" placeholder="请选择门店" style="width: 300px;">
                <el-option
                  v-for="items in (OptionObj.stoerOption as any)" :key="items.id" :label="`${items.id}-${items.storeName}`" :value="items.id"
                />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="轮播图">
              <ImagesUpload
                :height="300" :width="200" :size="5"
                :url="(ruleForm.bannerJson as string[])" :max="10" :ext="['jpg', 'png']"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="企微二维码图片">
              <ImageUpload
                :ext="['jpg', 'png']"
                :size="5" :max="1"
                width="auto"
                :url="ruleForm.qvQrCodePic"
                @on-success="(url) => handleUploadSuccess(url)"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData()">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
